package com.cntv.lifecycledemo.java;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/**
 * Created By Mahongyin
 * Date    2020/9/17 9:50
 * 自定绑定生命周期的计时器   被观察者 暂停时 计时器也暂停   页面恢复时 计时也恢复。
 */
public class AutoLifeCycleChronometer extends Chronometer implements LifecycleObserver {
    private long eleTime;

    public AutoLifeCycleChronometer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void activityResume() {
        setBase(SystemClock.elapsedRealtime() - eleTime);//设置始终起始位置
        start();//页面显示时开始计时
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void activityPause() {
        eleTime = SystemClock.elapsedRealtime() - getBase();//记录时钟暂停位置
        stop();
    }

}
